<!-- 站点编辑弹窗 -->
<template>
  <el-dialog :destroy-on-close="true" :lock-scroll="false" :title="isUpdate?'修改产品':'添加产品'" :visible="visible"
             width="750px" @update:visible="updateVisible">
    <el-form ref="form" :model="form" :rules="rules" label-width="82px">
      <el-form-item label="所属客户" prop="customer_name">
        <el-autocomplete v-model="customer_name" :fetch-suggestions="querySearchCustomer" placeholder="请搜索所属客户"
                         value-key="name" @select="handleSelectCustomer">
          <template slot-scope="{ item }">
            <div style="color: #333;"><b>{{ item ? item.name : '' }}</b></div>
            <div class="name" style="margin-top: -4px; display: flex;">
              电话: <span style="margin-right: 14px;">{{ item.user ? item.user.phone : '无' }}</span>
              编号: <span style="margin-right: 14px;">{{ item.customer_number }}</span>
              联系人: <span>{{ item.user ? item.user.name : '无联系人' }}</span>
            </div>
          </template>
        </el-autocomplete>
      </el-form-item>
      <el-form-item label="产品名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入产品名称" />
      </el-form-item>
      <el-form-item label="产品类型" prop="type">
        <el-autocomplete v-model="type_name" :fetch-suggestions="querySearchType" placeholder="请搜索产品类型"
                         value-key="name" @select="selectProductItem" />
      </el-form-item>
      <el-form-item label="服务网点:" prop="department_id">
        <el-select
          v-model="form.department_id"
          class="ele-block"
          clearable
          placeholder="请选择服务网点">
          <el-option
            v-for="(item, index) in deptLists"
            :key="index"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="安装地址" prop="install_address">
        <el-input v-model="form.install_address" placeholder="请输入安装地址" />
      </el-form-item>
      <el-form-item label="购买日期" prop="date_buy">
        <el-date-picker v-model="form.date_buy" class="c-picker" placeholder="选择购买日期" type="date"
                        value-format="yyyy-MM-dd" />
      </el-form-item>
      <el-form-item label="验收日期" prop="date_check">
        <el-date-picker v-model="form.date_check" class="c-picker" placeholder="选择验收日期" type="date"
                        value-format="yyyy-MM-dd" />
      </el-form-item>
      <el-form-item label="出厂报告">
        <template>
          <el-upload
            :file-list="fileList"
            :http-request="upload"
            :limit="1"
            :on-change="uploadHandleChange"
            :show-file-list="false"
            accept=".xls,.xlsx,.docx,application/msword,application/vnd.ms-excel,application/pdf"
            action="#"
            class="upload-demo"
            multiple
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传xls/xlsx/docx/pdf文件，且不超过10m</div>
          </el-upload>

          <span v-if="!form.attachment==''" key="1" style="color: deepskyblue">
            {{ form.attachment }}
            <span style="cursor: pointer;color: black" @click="delAttachment">&nbsp;&nbsp;删除</span></span>
        </template>
      </el-form-item>
      <el-form-item label="保质期">
        <template>
          <el-radio-group v-model="radio" @change="selectType">
            <el-radio v-model="form.warranty_type" label="at">自动计算</el-radio>
            <el-radio v-model="form.warranty_type" label="mt">手动添加</el-radio>
          </el-radio-group>
        </template>
        <template>
          <div v-if="form.type_name && form.warranty_type === 'at'" class="p-3 bg-gray-100 mb-2 leading-normal">
            <div class="mb-1 text-black">计算规则</div>
            <div class="text-xs">
              质保期时长：{{ productType ? productType.warranty_cycle_count : '' }}
              {{ productType ? productType.warranty_start_unit : '' }}
            </div>
          </div>

          <div v-if="type_name || form.warranty_type === 'mt'">
            <el-date-picker v-model="form.warranty_start" class="c-picker" placeholder="质保开始日期" size="small"
                            type="date" value-format="yyyy-MM-dd" @change="changeStartTime" />
            <el-date-picker v-model="form.warranty_end" :disabled="form.warranty_type === 'at'"
                            :picker-options="endTimeOptions" placeholder="质保结束日期" size="small" type="date"
                            value-format="yyyy-MM-dd" />
            <div>质保状态: {{ expirationStatus }}</div>
          </div>
        </template>
        <el-alert v-if="form.warranty_type === 'at' && !type_name" :closable="false" class="h-8 py-0" show-icon
                  title="未选择产品类型，无法进行自动计算。请选择&quot;产品类型&quot;或&quot;手动添加&quot;"
                  type="warning" />
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button @click="cancel">取消</el-button>
      <el-button :loading="loading" type="primary" @click="save">保存</el-button>
    </div>
  </el-dialog>
</template>

<script>
import regions from 'ele-admin/packages/regions';
import Moment from 'moment';

export default {
  components: {},
  name: 'ProductEdit',
  props: {
    // 弹窗是否打开
    visible: Boolean,
    // 修改回显的数据
    data: Object
  },
  data() {
    return {
      fileList: [],
      attachmentUrl: '',
      //选择文件保质期方式
      radio: 'at',
      regions: regions,
      // 选中的省市区
      city: [],
      // 选中的省市
      provinceCity: [],
      // 选中的省
      province: [],
      // 表单数据
      form: Object.assign({ status: 1 }, this.data),
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false,
      customer_name: "",
      type_name: "",
      endTimeOptions: {}, // 保质期结束时间
      productType: null, // 商品类型
      deptLists: [],
      //验证
      rules: {
        name: [
          { required: true, message: "请输入产品名称", trigger: "blur" }
        ],
        // type: [{
        //   required: true, trigger: "blur", validator: (rule, value, callback) => {
        //     !this.form.type_name ? callback(new Error("请搜索产品类型")) : callback;
        //   }
        // }],
        // customer_name: [{
        //   required: true, trigger: "blur", validator: (rule, value, callback) => {
        //     !this.form.customer_name ? callback(new Error("请搜索所属客户")) : callback;
        //   }
        // }],
        install_address: [
          { required: true, message: "请输入详细地址", trigger: "blur" }
        ],
        department_id: [
          { required: true, message: "请选择服务网点", trigger: "change" }
        ],
        date_buy: [
          { required: true, message: "请选择购买日期", trigger: "blur" }
        ],
        date_check: [
          { required: true, message: "请选择验收日期", trigger: "blur" }
        ],
        address: [
          { required: true, message: "请输入详细地址", trigger: "blur" }
        ],
      },
    };
  },
  computed: {
    expirationStatus() {
      if (!this.form.warranty_start) {
        return '请选择日期';
      }
      // this.form.warranty_end 小于当前时间，为保外
      if (this.form.warranty_end < Moment().format('YYYY-MM-DD')) {
        return '保外';
      } else {
        return '保内';
      }
    }
  },
  watch: {
    data() {
      if (this.data) {
        this.data.customer ? this.customer_name = this.data.customer.name : this.customer_name = "";
        this.type_name = this.data.type ? this.data.type.name : '';
        this.form.attachment = this.data.attachment;
        this.form = Object.assign(this.data);
        this.isUpdate = true;
      } else {
        this.form = {};
        this.city = [];
        this.customer_name = "";
        this.type_name = "";
        this.isUpdate = false;
      }
    },
    visible() {
      this.form.warranty_type = 'at'
    }
  },
  mounted() {
    this.getDeptList();
  },
  methods: {
    delAttachment() {
      this.fileList = []
      this.form.attachment = ''
    },
    inputArea(val) {
      if (val) {
        this.$nextTick(() => {
          this.$refs.form.clearValidate('city');
        })
      }
    },
    uploadHandleChange(file) {
      if (file.status === "error") {
        this.$message.error("上传失败");
      }
    },
    upload(file) {
      const formData = new FormData();
      formData.append("attachment", file.file);
      this.$http.post("files/filesStore", formData).then((res) => {
        this.form.attachment = res.data.data.path;
        //聚焦刷新
        this.$forceUpdate()
      });
    },
    //选择文件保质期类型
    selectType(val) {
      this.form.warranty_type = val
      this.$forceUpdate()
    },
    //获取deptList
    getDeptList() {
      const loading = this.$loading({ lock: true });
      this.$http.get('/dept/index').then(res => {
        loading.close();
        if (res.data.code === 0) {
          this.deptLists = res.data.data.filter(item => {
            if (item.type == 3) {
              return item
            }
          })
        } else {
          this.$message.error(res.data.msg);
        }
      }).catch(e => {
        loading.close();
        this.$message.error(e.message);
      });
    },
    /* 保存编辑 */
    save() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.loading = true;
          // 编辑
          if (this.isUpdate) {
            this.$emit("editProduct", this.form, this.form.id);
          } else {
            // 新增
            this.$emit("addProduct", this.form);
          }
        } else {
          return false;
        }
      });
    },
    cancel() {
      this.updateVisible(false);
      this.customer_name = "";
      this.type_name = "";
      this.form = {};
    },
    /* 更新visible */
    updateVisible(value) {
      if (!this.isUpdate) {
        this.form = {}
      }
      this.$emit('update:visible', value);
    },
    querySearchCustomer(query, cb) {
      this.$http.get("customers", {
        params: {
          keyword: query,
          page: 1,
          limit: 10
        }
      }).then((res) => {
        cb(res.data.data);
      });
    },
    handleSelectCustomer(item) {
      this.$refs.form.clearValidate('customer_name')
      this.form.customer_id = item.id;
      this.form.customer_name=item.name
    },
    querySearchType(query, cb) {
      this.$http.get("product_types", {
        params: {
          name: query,
          page: 1,
          limit: 10
        }
      }).then((res) => {
        cb(res.data.data);
      });
    },
    selectProductItem(item) {
      this.productType = item
      this.form.type_id = item.id;
      this.form.type_name=item.name
      this.$refs.form.clearValidate('type')
    },
    changeStartTime() {
      // 当 form.warranty_type 为 at 自动计算时，保质期结束时间自动计算 + 质保期时长
      if (this.form.warranty_type !== 'mt') {
        this.form.warranty_end = Moment(this.form.warranty_start).add(this.productType.warranty_cycle_count, this.productType.warranty_start_unit).format('YYYY-MM-DD');
        this.$forceUpdate()
      }
    },
  }
}
</script>

<style scoped>
</style>
